<template>
  <el-container>
    <el-main class="main-bg">
      <el-form ref="form" :model="form" class="form-list-card-out" label-width="80px">
        <el-form-item v-if="!userInfo.unitId" :required="true" label="部门名称">
          <el-select
            v-model="unitId"
            placeholder="请选择"
            value-key="unitId"
            @change="(val) => onChange(val, 'unitName', 'unitId')"
          >
            <el-option v-for="item in unitList" :key="item.unitName" :label="item.unitName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item v-else :required="true" label="部门名称">
          <el-input v-model="form.unitName" placeholder="请输入" readonly />
        </el-form-item>
        <el-form-item :required="true" label="日期">
          <el-date-picker
            v-model="form.dateTime"
            :picker-options="pickerOptions"
            placeholder="选择日期"
            style="width: 100%"
            type="date"
            value-format="timestamp"
            @change="onChangeTime"
          />
        </el-form-item>
        <el-form-item :required="true" label="类别">
          <el-select
            v-model="sortId"
            placeholder="请选择"
            value-key="sortId"
            @change="(val) => onChange(val, 'sortName', 'sortId')"
          >
            <el-option v-for="item in sortList" :key="item.sortName" :label="item.sortName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item :required="true" label="所属仓库">
          <el-select
            v-model="warehouseId"
            placeholder="请选择"
            value-key="warehouseId"
            @change="(val) => onChange(val, 'warehouse', 'warehouseId')"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseName"
              :label="item.warehouseName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model="form.number" placeholder="请输入" readonly />
        </el-form-item>
        <el-form-item label="明细" required>
          <Table
            ref="table"
            :border="true"
            :current-page="page"
            :header-data="form.id ? tableHeader1 : tableHeader"
            :loading="loading"
            :show-pagination="false"
            :span-method="true"
            :table-data="tableData"
            :total="total"
            class="data-table"
            style="width: 100%"
          />
          <el-button v-if="!form.id" class="add-item" size="small" type="primary" @click="onAddItem">增加一行
          </el-button>
        </el-form-item>
        <el-form-item :required="true" label="备注">
          <el-input v-model="form.remark" maxlength="60" placeholder="请输入" show-word-limit type="textarea" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合计金额">
              <el-input v-model="form.totalAmountChinese" placeholder="请输入" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="¥">
              <el-input v-model="form.totalAmount" placeholder="请输入" readonly>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item :required="true" label="主管">-->
        <!--          <el-input v-model="form.manager" placeholder="请输入"/>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item :required="true" label="记账">-->
        <!--          <el-input v-model="form.accountName" placeholder="请输入"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item :required="true" label="经手人">-->
        <!--          <el-input v-model="form.handledName" placeholder="请输入"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <div class="footer">
        <el-button @click="onBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import addTable from "@/mixins/addtable";
import {
  getUnitList,
  getSortList,
  postOutBoundAdd,
  allGoodsList,
  getMaxOutNumber,
  getOutBoundDetail,
  postOutBoundUpdate,
} from "./api";
import { digitUppercase } from "@/utils";
import OutBoundNum from "../outBound/inBoundNum.vue";
import { parseTime } from "@/utils";
import { mapGetters } from "vuex";
import { manWithWarehouse } from "@/views/warehouse/api";

export default {
  name: "Inbound",
  mixins: [addTable],
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now();
        },
      },
      searchForm: {
        sortName: "",
      },
      tableData: [
        {
          outBoundId: "",
          outBoundType: "",
          outBoundUnitName: "",
          outBoundNum: 0,
          outBoundPrice: 0,
          outBoundMoney: 0,
          remark: "",
        },
      ],
      unitList: [],
      sortList: [],
      warehouseList: [],
      type: "look",
      tableHeader: [],
      personOptions: [],
      tableHeader1: [],
      oneLoading: false,
      drawerVisible: false,
      unitId: "",
      sortId: "",
      warehouseId: "",
      form: {
        unitId: "",
        unitName: "",
        dateTime: null,
        sortId: "",
        sortName: "",
        number: "",
        totalAmount: 0,
        totalAmountChinese: "",
        manager: "",
        warehouse: "",
        warehouseId: "",
        accountName: "",
        handledName: "",
        remark: "",
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    tableData: {
      handler (val) {
        val.map((item) => {
          item.outBoundMoney = (item.outBoundPrice * item.outBoundNum).toFixed(
            2
          );
          return item;
        });
        this.form.totalAmount = val.reduce(
          (accumulator, currentValue) =>
            accumulator + currentValue.outBoundMoney * 1,
          0
        );
        this.form.totalAmount = this.form.totalAmount.toFixed(2);
        this.form.totalAmountChinese = digitUppercase(this.form.totalAmount);
      },
      deep: true,
      immediate: true,
    },
  },
  async created () {
    this.tableHeader = [
      {
        prop: "outBoundId",
        label: "名称",
        sortable: false,
        width: 350,
        overflow: true,
        align: "left",
        component: "el-select",
        required: true,
        options: [],
        attrs: {
          filterable: true,
        },
        listeners: {
          change (row, val, $index, config) {
            console.log("this1----row", row);
            const res = config.options.find(
              (item) => item.value === row.outBoundId
            );
            row.outBoundType = res.inBoundType;
            // row.outBoundUnitName = res.outBoundUnitName
            row.outBoundUnitName = res.inBoundUnitName;
            row.outBoundPrice = res.inBoundPrice;
            row.outBoundNum = 0;
            row.outBoundName = res.inBoundName;
            row.storeNum = res.storeNum;
          },
        },
      },
      {
        prop: "outBoundType",
        label: "规格",
        sortable: false,
        overflow: true,
        align: "left",
        required: true,
      },
      {
        prop: "outBoundUnitName",
        label: "单位",
        sortable: false,
        overflow: true,
        align: "left",
        required: true,
      },
      {
        prop: "outBoundNum",
        label: "出库数量",
        sortable: false,
        overflow: true,
        align: "left",
        component: OutBoundNum,
        required: true,
        componentProps: {},
        // attrs: {
        //   type: 'number',
        // },
        // listeners: {
        //   change(row, val, $index, config) {
        //     if (row.outBoundNum > row.outBoundNumMax) {
        //       row.outBoundNum = row.outBoundNumMax
        //     }
        //   }
        // }
      },
      {
        prop: "storeNum",
        label: "库存数量",
        sortable: false,
        overflow: true,
        align: "left",
        required: true,
      },
      {
        prop: "outBoundPrice",
        label: "单价",
        sortable: false,
        overflow: true,
        align: "left",
        required: true,
      },
      {
        prop: "outBoundMoney",
        label: "金额",
        sortable: false,
        overflow: true,
        align: "left",
      },
      // {
      //   prop: 'remark',
      //   label: '备注',
      //   sortable: false,
      //   overflow: true,
      //   align: 'left',
      //   component: 'el-input',
      //   required: true,
      //   attrs: {
      //     type: 'textarea'
      //   }
      // },
      {
        width: 80,
        label: "操作",
        align: "left",
        fixed: "right",
        buttonList: (row, index) => {
          const arr = [];
          if (index !== 0) {
            arr.push({
              text: "删除",
              type: "text",
              event: this.onDelete,
            });
          }
          return arr;
        },
      },
    ];
    this.tableHeader1 = [
      {
        prop: "outBoundName",
        label: "名称",
        sortable: false,
        width: 350,
        overflow: true,
      },
      {
        prop: "outBoundType",
        label: "规格",
        sortable: false,
        overflow: true,
        align: "left",
        required: true,
      },
      {
        prop: "outBoundUnitName",
        label: "单位",
        sortable: false,
        overflow: true,
        align: "left",
        required: true,
      },
      {
        prop: "outBoundNum",
        label: "出库数量",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "storeNum",
        label: "库存数量",
        sortable: false,
        overflow: true,
        align: "left",
        required: true,
      },
      {
        prop: "outBoundPrice",
        label: "单价",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "outBoundMoney",
        label: "金额",
        sortable: false,
        overflow: true,
        align: "left",
      },
    ];
    await this.getInitData();
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id;
      this.getDetail();
    } else {
      this.form.unitName = this.userInfo.unitName;
      this.form.unitId = this.userInfo.unitId;
      this.form.role = this.userInfo.role;
      this.form.userName = this.userInfo.userName;
      this.form.userId = this.userInfo.userId;
      this.form.dateTime = Date.now();
    }
  },
  methods: {
    getDetail () {
      getOutBoundDetail({ id: this.form.id })
        .then(async (res) => {
          if (!res) return;
          const { data } = res;
          this.form = {
            ...data,
          };
          this.unitId = data.unitId;
          this.sortId = {
            sortId: data.sortId,
            sortName: data.sortName,
          };
          this.warehouseId = {
            warehouseId: data.warehouseId,
            warehouseName: data.warehouseName,
          };
          this.tableData = data.subTable;
          await this.getBoundList();
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });
    },
    async onChange (val, type, id) {
      this.form[type] = val[type];
      this.form[id] = val[id];
      if (type === "warehouse") {
        this.tableData = [
          {
            outBoundId: "",
            outBoundType: "",
            outBoundUnitName: "",
            outBoundNum: 0,
            outBoundPrice: 0,
            outBoundMoney: 0,
            remark: "",
          },
        ];
        if (this.form.warehouseId && !this.form.id) {
          this.getAjaxMaxNumber();
          await this.getBoundList();
        }
      }
    },
    onChangeTime () {
      if (!this.form.id) {
        this.getAjaxMaxNumber();
      }
    },
    async getAjaxMaxNumber () {
      if (this.form.warehouseId && this.form.dateTime) {
        const { data } = await getMaxOutNumber({
          warehouseId: this.form.warehouseId,
          dateTime: this.form.dateTime,
        });
        this.form.number = data.newInBoundNo;
      }
    },
    async getBoundList () {
      if (this.form.warehouseId) {
        const res = await allGoodsList({ warehouseId: this.form.warehouseId });
        const boundList = res.data.map((item) => {
          item.value = item.id;
          item.label = item.inBoundName + `(${parseTime(item.createdTime)})`;
          return item;
        });
        this.tableHeader[0].options = boundList.filter(
          (item) => item.storeNum !== 0
        );
      }
    },
    async getInitData () {
      const { data } = await getUnitList({
        page: 1,
        limit: 1000,
      });
      this.unitList = data;
      const res = await getSortList({
        page: 1,
        limit: 1000,
        sortType: "1", // 类型
      });
      this.sortList = res.data;

      const result = await manWithWarehouse();
      this.warehouseList = result.data.map((item) => {
        item.warehouse = item.warehouseName;
        return item;
      });
    },
    onAddItem () {
      if (this.tableData.length >= 5) {
        this.$message.warning("最多只能录入5条记录");
        return;
      }
      this.tableData.push({
        outBoundId: "",
        outBoundType: "",
        outBoundUnitName: "",
        outBoundNum: 0,
        outBoundPrice: 0,
        outBoundMoney: 0,
      });
    },
    onDelete (row, index) {
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.tableData.splice(index, 1);
      });
    },
    onBack () {
      this.$router.back();
    },
    handleSubmit () {
      const regex = /^\d+(\.\d*)?$/; // 修改正则表达式，允许小数点后没有数字
      // //对客户端的数据进行校验
      if (!this.form.unitName) {
        this.$message.error("单位名称不能为空");
        return;
      }
      if (!this.form.dateTime) {
        this.$message.error("日期不能为空");
        return;
      }
      if (!this.form.sortName) {
        this.$message.error("类别名称不能为空");
        return;
      }
      if (!this.form.warehouse) {
        this.$message.error("仓库名称不能为空");
        return;
      }
      if (!this.form.remark) {
        this.$message.error(`明细备注不能为空！`);
        return; // 在验证失败时中断执行
      }
      const subTable = this.tableData.map((item) => {
        item.inventoryNum = item.storeNum - item.outBoundNum;
        return item;
      });
      for (let i = 0; i < this.tableData.length; i++) {
        const outBoundId = this.tableData[i].outBoundId;
        const outBoundNum = this.tableData[i].outBoundNum;
        const outBoundPrice = this.tableData[i].outBoundPrice;
        if (!outBoundId) {
          this.$message.error(`明细第${i + 1}行名称不能为空！`);
          return; // 在验证失败时中断执行
        }
        if (!outBoundNum) {
          this.$message.error(`明细第${i + 1}出库数量不能为空！`);
          return; // 在验证失败时中断执行
        }
        if (!regex.test(outBoundPrice)) {
          this.$message.error(`明细第${i + 1}行金额格式不正确！`);
          return; // 在验证失败时中断执行
        }

        if (!regex.test(outBoundNum)) {
          this.$message.error(`明细第${i + 1}行数量格式不正确！`);
          return; // 在验证失败时中断执行
        }
      }
      const idSet = new Set();
      // 使用 some 方法遍历数组
      const hasDuplicateId = subTable.some((item) => {
        if (idSet.has(item.outBoundId)) {
          return true; // 数组中存在相同的 id
        } else {
          idSet.add(item.outBoundId); // 将当前 id 添加到 Set 中
          return false; // 没有相同的 id
        }
      });
      if (hasDuplicateId) {
        this.$message.error("明细中含有相同项，请修改！");
        return;
      }

      // if (!this.form.accountName) {
      //   this.$message.error('记账不能为空')
      //   return
      // }
      // if (!this.form.handledName) {
      //   this.$message.error('经手人不能为空')
      //   return
      // }
      this.form.id
        ? postOutBoundUpdate({ ...this.form, subTable }).then(
          ({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.form = {};
            this.onBack();
          }
        )
        : postOutBoundAdd({ ...this.form, subTable: this.tableData }).then(
          ({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.form = {};
            this.onBack();
          }
        );
    },
  },
};
</script>
<style lang="scss" scoped>
.form-list-card-out {
  width: 100%;

  .form-list {
    width: 100%;

    .title {
      width: 100%;
      text-align: center;
      font-size: 30px;
      font-weight: bold;
      margin-bottom: 16px;
    }

    .el-col {
      display: flex;
      align-items: center;

      span {
        display: inline-block;
        white-space: nowrap;
        margin: 0 6px;
      }

      .el-input {
        margin: 0 6px;

        .el-input__inner {
          border: none;
        }
      }
    }
  }
}
</style>
